using CSUtils;
using Spine;
using Spine.Unity;
using UnityEngine;

public static class CSpineUtils {
    public static bool SpineChangeSkin(this GameObject go, string skinName) => SpineChangeSkin(go?.transform, skinName);

    public static bool SpineChangeSkin(this Component comp, string skinName) {
        if (comp == null) {
            return false;
        }
        var skeletonRenderer = comp.GetComponentInChildren<SkeletonRenderer>();
        return SpineChangeSkin(skeletonRenderer, skinName);
    }

    public static bool SpineChangeSkin(this SkeletonRenderer sr, string skinName) {
        if (sr == null || sr.skeleton == null) {
            return false;
        }
        var isSuccess = SpineChangeSkin(sr.skeleton, skinName);
        sr.LateUpdate(); // 更新渲染器状态
        return isSuccess;
    }

    public static bool SpineChangeSkin(this Skeleton skeleton, string skinName) {
        if (skeleton == null) {
            return false;
        }
        var newSkin = skeleton.Data.FindSkin(skinName);
        return SpineChangeSkin(skeleton, newSkin);
    }

    public static bool SpineChangeSkin(this Skeleton skeleton, Skin newSkin) {
        if (skeleton == null || newSkin == null) {
            //Debug.LogError($"皮肤未找到...{sr.name}......skinName={skinName}");
            return false;
        }

        //var newSkin2 = skeleton.Data.SkinSet.AddSkin(newSkin, skeleton.Data);
        skeleton.SetSkin(newSkin);
        skeleton.SetSlotsToSetupPose(); // 重置插槽到初始状态
        skeleton.UpdateWorldTransform(); // 更新骨骼变换 
        return true;
    }
}
